package com.wondersgroup.retrofittest.mall;

import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.hss.rxjava.bean.GoodsBean;
import com.wondersgroup.retrofittest.R;
import com.wondersgroup.retrofittest.TextViewHolder;

import java.util.List;

/**
 * Created by Administrator on 2017/1/24.
 */

public class RecyclerGoodsAdapter extends RecyclerView.Adapter<TextViewHolder> {
    SparseArray<GoodsBean> sparseArray;
    @Override
    public TextViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new TextViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_text,parent,false));
    }

    @Override
    public void onBindViewHolder(TextViewHolder holder, int position) {
        holder.tv_name.setText(sparseArray.get(position).title);
    }

    @Override
    public int getItemCount() {
        return sparseArray == null ? 0 : sparseArray.size();
    }

    public RecyclerGoodsAdapter() {
    }

    public void setData(SparseArray<GoodsBean> arr){
        if (sparseArray != null){
            sparseArray.clear();
        }
        sparseArray = arr;
    }
    public void setData(List<GoodsBean> list) {
        if (sparseArray == null){
            sparseArray = new SparseArray<>();
        }else {
            sparseArray.clear();
        }

        for (int i=0,size = list.size(); i<size; i++){
            sparseArray.append(i,list.get(i));
        }
        notifyDataSetChanged();
    }

    public void setData(GoodsBean[] arr) {
        if (sparseArray == null){
            sparseArray = new SparseArray<>();
        }else {
            sparseArray.clear();
        }
        if (arr != null && arr.length > 0) {
            for (int i = 0, size = arr.length; i < size; i++) {
                this.sparseArray.append(i,arr[i]);
            }
        }
        notifyDataSetChanged();
    }

    public void addItem(GoodsBean str){
        if (sparseArray == null){
            sparseArray = new SparseArray<>();
        }
        sparseArray.append(sparseArray.size(),str);
    }

    public void addList(List<GoodsBean> list){
        if (list == null || list.size() == 0){
            return;
        }
        if (sparseArray == null){
            sparseArray = new SparseArray<>();
        }

        int i= sparseArray.size();
        int start = i;
        for (GoodsBean item : list){
            sparseArray.append(i++,item);
        }
//        notifyItemRangeChanged(start,list.size());
        notifyDataSetChanged();
    }
}
